<?php

namespace App\Controller\Wap;

use App\Base\BaseController4User;
use BaseExt\SmsChanglan;
use App\Model\LazyCommon\UserModel;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Validation;

/**
 * @route("/sms")
 */
class SmsCodeController extends BaseController4User
{


    private function checkPhone($phone)
    {
        $validator = Validation::createValidator();
        return count($validator->validate($phone,array(
            new NotBlank(),
            new Regex('/^0?(13|14|15|16|17|18|19)[0-9]{9}$/')
        )));
    }


    /**
     * @route("/get/code/wechat",name="UserAppSmsGetCodeWeChat")
     */
    public function UserAppSmsGetCodeWeChat(Request $request)
    {

        if(!$phone = $this->getParamRequired("phone")){return $this->json_out(0,"手机号错误");}
        if($this->checkPhone($phone)){
            return $this->json_out(0,"手机号验证错误");
        }

        $openid = $this->getOpenid();
        if (!$openid) {
            return $this->json_out(0,"请从微信公众平台访问此页面");
        }

        $sms_time = (int)$this->getSessionData("sms_start_time");
        if ($sms_time > 0 && $sms_time > time() - 60) {
            return $this->json_out(0,"操作过于频繁",$sms_time);
        }

        $sms_num = $this->getSessionData("sms_num");
        if ($sms_num > 5) {
            return $this->json_out(0,"操作过于频繁,请24小时候再试");
        }

        $Model = new UserModel($this->getDoctrine());
        $Model->getByWeChetId($openid);


        $code = rand(1000,9999);
        $smsData["sms_num"] = (int)$this->getSessionData("sms_num")  + 1;
        $smsData["sms_start_time"] = time();
        $smsData["sms_end_time"] = time();
        $smsData["sms_code"] = $code;
        $smsData["sms_phone"] = $phone;
        $this->setSessionData($smsData);

        $SmsChanglan = new SmsChanglan();
        $erro = $SmsChanglan->sendSms($phone,"【萱氧】您的验证码为$code , 有效期5分钟");
        if ($erro) {

            return $this->json_out(0,$erro);
        }
        return $this->json_out(1,"验证码已发送",$code);
    }


}
